/**
 * 图表容器组件
 * 提供统一的图表容器，支持Chart.js和ECharts
 */
class ChartContainer extends BaseComponent {
    constructor(options = {}) {
        super({
            ...options,
            className: `chart-container ${options.className || ''}`
        });

        // 组件配置
        this.title = options.title || '';
        this.subtitle = options.subtitle || '';
        this.type = options.type || 'chartjs'; // 'chartjs' or 'echarts'
        this.height = options.height || 400;
        this.showActions = options.showActions !== false;
        this.responsive = options.responsive !== false;
        this.loading = false;
        this.error = null;

        // 图表配置
        this.chartConfig = options.chartConfig || {};
        this.chartData = options.chartData || null;
        this.chartOptions = options.chartOptions || {};

        // 图表实例
        this.chartInstance = null;

        // 回调函数
        this.onDataLoad = options.onDataLoad || null;
        this.onChartClick = options.onChartClick || null;
        this.onDownload = options.onDownload || null;

        // 初始化
        this.initializeChart();
    }

    /**
     * 初始化图表
     */
    initializeChart() {
        // 确保图表库已加载
        if (this.type === 'chartjs' && typeof Chart === 'undefined') {
            console.warn('Chart.js is not loaded');
            return;
        }

        if (this.type === 'echarts' && typeof echarts === 'undefined') {
            console.warn('ECharts is not loaded');
            return;
        }
    }

    /**
     * 渲染图表容器
     */
    render() {
        const template = `
            <div class="chart-container-wrapper ${this.className}" data-component-id="${this.id}">
                <div class="bg-white rounded-lg border border-slate-200 shadow-sm overflow-hidden">
                    ${this.renderHeader()}
                    ${this.renderBody()}
                </div>
            </div>
        `;

        // 创建或更新元素
        if (!this.element) {
            this.element = this.createElementFromTemplate(template);
        } else {
            this.element.outerHTML = template;
            this.element = this.container.querySelector(`[data-component-id="${this.id}"]`);
        }

        // 创建图表
        this.createChart();

        // 绑定事件
        this.bindEvents();

        // 设置响应式
        if (this.responsive) {
            this.setupResponsive();
        }
    }

    /**
     * 渲染头部
     */
    renderHeader() {
        return `
            <div class="px-6 py-4 border-b border-slate-200">
                <div class="flex items-center justify-between">
                    <div class="flex-1">
                        <h3 class="text-lg font-semibold text-slate-800 mb-1">${this.title}</h3>
                        ${this.subtitle ? `<p class="text-sm text-slate-500">${this.subtitle}</p>` : ''}
                    </div>
                    <div class="flex items-center space-x-2">
                        ${this.showActions ? `
                            <button class="refresh-btn p-2 text-slate-500 hover:text-slate-700 hover:bg-slate-100 rounded-lg transition-colors" title="刷新">
                                <i class="fas fa-sync-alt"></i>
                            </button>
                            <button class="download-btn p-2 text-slate-500 hover:text-slate-700 hover:bg-slate-100 rounded-lg transition-colors" title="下载">
                                <i class="fas fa-download"></i>
                            </button>
                            <button class="fullscreen-btn p-2 text-slate-500 hover:text-slate-700 hover:bg-slate-100 rounded-lg transition-colors" title="全屏">
                                <i class="fas fa-expand"></i>
                            </button>
                        ` : ''}
                    </div>
                </div>
            </div>
        `;
    }

    /**
     * 渲染主体
     */
    renderBody() {
        const loadingOverlay = this.loading ? `
            <div class="absolute inset-0 bg-white bg-opacity-75 flex items-center justify-center z-10">
                <div class="text-center">
                    <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
                    <p class="mt-2 text-sm text-slate-600">加载中...</p>
                </div>
            </div>
        ` : '';

        const errorOverlay = this.error ? `
            <div class="absolute inset-0 bg-red-50 flex items-center justify-center z-10">
                <div class="text-center">
                    <i class="fas fa-exclamation-triangle text-red-500 text-2xl mb-2"></i>
                    <p class="text-sm text-red-600">${this.error}</p>
                    <button class="retry-btn mt-2 px-3 py-1 text-sm bg-red-600 text-white rounded hover:bg-red-700">
                        重试
                    </button>
                </div>
            </div>
        ` : '';

        return `
            <div class="relative" style="height: ${this.height}px;">
                <canvas id="${this.id}_canvas" class="w-full h-full"></canvas>
                ${loadingOverlay}
                ${errorOverlay}
            </div>
        `;
    }

    /**
     * 从模板创建元素
     */
    createElementFromTemplate(template) {
        const div = document.createElement('div');
        div.innerHTML = template.trim();
        return div.firstElementChild;
    }

    /**
     * 创建图表
     */
    createChart() {
        if (!this.element) return;

        const canvas = this.element.querySelector('canvas');
        if (!canvas) return;

        try {
            if (this.type === 'chartjs') {
                this.createChartJS(canvas);
            } else if (this.type === 'echarts') {
                this.createECharts(canvas);
            }
        } catch (error) {
            console.error('Chart creation failed:', error);
            this.showError('图表创建失败');
        }
    }

    /**
     * 创建Chart.js图表
     */
    createChartJS(canvas) {
        const ctx = canvas.getContext('2d');

        // 销毁旧实例
        if (this.chartInstance) {
            this.chartInstance.destroy();
        }

        // 创建新实例
        this.chartInstance = new Chart(ctx, {
            type: this.chartConfig.type || 'line',
            data: this.chartData || this.getDefaultData(),
            options: this.getChartJSOptions()
        });

        // 绑定点击事件
        canvas.onclick = (event) => {
            const points = this.chartInstance.getElementsAtEventForMode(event, 'nearest', { intersect: true }, true);
            if (points.length) {
                const firstPoint = points[0];
                const label = this.chartInstance.data.labels[firstPoint.index];
                const value = this.chartInstance.data.datasets[firstPoint.datasetIndex].data[firstPoint.index];
                this.emit('chartClick', { label, value, datasetIndex: firstPoint.datasetIndex, index: firstPoint.index });

                if (this.onChartClick) {
                    this.onChartClick.call(this, { label, value, datasetIndex: firstPoint.datasetIndex, index: firstPoint.index });
                }
            }
        };
    }

    /**
     * 创建ECharts图表
     */
    createECharts(canvas) {
        // 销毁旧实例
        if (this.chartInstance) {
            this.chartInstance.dispose();
        }

        // 创建新实例
        this.chartInstance = echarts.init(canvas);

        // 设置配置
        const option = {
            ...this.chartConfig,
            ...this.getEChartsOptions()
        };

        this.chartInstance.setOption(option);

        // 绑定点击事件
        this.chartInstance.on('click', (params) => {
            this.emit('chartClick', params);
            if (this.onChartClick) {
                this.onChartClick.call(this, params);
            }
        });
    }

    /**
     * 获取Chart.js配置
     */
    getChartJSOptions() {
        const defaultOptions = {
            responsive: this.responsive,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                    labels: {
                        usePointStyle: true,
                        padding: 20
                    }
                },
                tooltip: {
                    mode: 'index',
                    intersect: false,
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    titleColor: '#fff',
                    bodyColor: '#fff',
                    borderColor: '#fff',
                    borderWidth: 1
                }
            },
            scales: {
                x: {
                    grid: {
                        display: false
                    }
                },
                y: {
                    beginAtZero: true,
                    grid: {
                        color: 'rgba(0, 0, 0, 0.05)'
                    }
                }
            },
            interaction: {
                mode: 'nearest',
                axis: 'x',
                intersect: false
            }
        };

        return {
            ...defaultOptions,
            ...this.chartOptions
        };
    }

    /**
     * 获取ECharts配置
     */
    getEChartsOptions() {
        const defaultOptions = {
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                },
                backgroundColor: 'rgba(0, 0, 0, 0.8)',
                textStyle: {
                    color: '#fff'
                }
            },
            legend: {
                type: 'scroll',
                orient: 'horizontal',
                top: 10,
                data: []
            }
        };

        return defaultOptions;
    }

    /**
     * 获取默认数据
     */
    getDefaultData() {
        return {
            labels: [],
            datasets: [{
                label: '数据',
                data: [],
                borderColor: 'rgb(59, 130, 246)',
                backgroundColor: 'rgba(59, 130, 246, 0.1)',
                tension: 0.4
            }]
        };
    }

    /**
     * 绑定事件
     */
    bindEvents() {
        if (!this.element) return;

        // 刷新按钮
        const refreshBtn = this.element.querySelector('.refresh-btn');
        if (refreshBtn) {
            refreshBtn.addEventListener('click', () => {
                this.refresh();
            });
        }

        // 下载按钮
        const downloadBtn = this.element.querySelector('.download-btn');
        if (downloadBtn) {
            downloadBtn.addEventListener('click', () => {
                this.download();
            });
        }

        // 全屏按钮
        const fullscreenBtn = this.element.querySelector('.fullscreen-btn');
        if (fullscreenBtn) {
            fullscreenBtn.addEventListener('click', () => {
                this.toggleFullscreen();
            });
        }

        // 重试按钮
        const retryBtn = this.element.querySelector('.retry-btn');
        if (retryBtn) {
            retryBtn.addEventListener('click', () => {
                this.retry();
            });
        }
    }

    /**
     * 设置响应式
     */
    setupResponsive() {
        if (!this.responsive) return;

        const resizeObserver = new ResizeObserver(() => {
            this.resize();
        });

        if (this.element) {
            resizeObserver.observe(this.element);
        }

        // 窗口大小变化
        window.addEventListener('resize', () => {
            this.resize();
        });
    }

    /**
     * 调整图表大小
     */
    resize() {
        if (this.chartInstance) {
            if (this.type === 'chartjs') {
                this.chartInstance.resize();
            } else if (this.type === 'echarts') {
                this.chartInstance.resize();
            }
        }
    }

    /**
     * 更新图表数据
     */
    updateData(data) {
        this.chartData = data;
        this.error = null;
        this.loading = false;

        if (this.chartInstance) {
            if (this.type === 'chartjs') {
                this.chartInstance.data = data;
                this.chartInstance.update();
            } else if (this.type === 'echarts') {
                this.chartInstance.setOption({
                    series: data.series || [],
                    xAxis: data.xAxis,
                    yAxis: data.yAxis
                });
            }
        }

        this.emit('dataUpdated', { data });
        return this;
    }

    /**
     * 刷新图表
     */
    refresh() {
        this.setLoading(true);
        this.emit('refresh');

        if (this.onDataLoad) {
            this.onDataLoad.call(this)
                .then(data => {
                    this.updateData(data);
                })
                .catch(error => {
                    this.showError('数据加载失败');
                    console.error('Data load failed:', error);
                })
                .finally(() => {
                    this.setLoading(false);
                });
        } else {
            setTimeout(() => {
                this.setLoading(false);
            }, 1000);
        }
    }

    /**
     * 下载图表
     */
    download() {
        if (!this.chartInstance) return;

        this.emit('download');

        if (this.onDownload) {
            this.onDownload.call(this);
            return;
        }

        // 默认下载实现
        const canvas = this.element.querySelector('canvas');
        if (canvas) {
            const link = document.createElement('a');
            link.download = `${this.title}_${new Date().toISOString().split('T')[0]}.png`;
            link.href = canvas.toDataURL();
            link.click();
        }
    }

    /**
     * 切换全屏
     */
    toggleFullscreen() {
        const container = this.element;

        if (!document.fullscreenElement) {
            container.requestFullscreen().then(() => {
                this.resize();
            });
        } else {
            document.exitFullscreen().then(() => {
                this.resize();
            });
        }
    }

    /**
     * 重试
     */
    retry() {
        this.error = null;
        this.refresh();
    }

    /**
     * 设置加载状态
     */
    setLoading(loading) {
        this.loading = loading;
        this.render();
        return this;
    }

    /**
     * 显示错误
     */
    showError(error) {
        this.error = error;
        this.loading = false;
        this.render();
        return this;
    }

    /**
     * 清除错误
     */
    clearError() {
        this.error = null;
        this.render();
        return this;
    }

    /**
     * 设置图表配置
     */
    setConfig(config) {
        this.chartConfig = config;
        this.render();
        return this;
    }

    /**
     * 设置图表选项
     */
    setOptions(options) {
        this.chartOptions = options;
        if (this.chartInstance) {
            if (this.type === 'chartjs') {
                this.chartInstance.options = this.getChartJSOptions();
                this.chartInstance.update();
            } else if (this.type === 'echarts') {
                this.chartInstance.setOption(options);
            }
        }
        return this;
    }

    /**
     * 设置标题
     */
    setTitle(title) {
        this.title = title;
        this.render();
        return this;
    }

    /**
     * 设置副标题
     */
    setSubtitle(subtitle) {
        this.subtitle = subtitle;
        this.render();
        return this;
    }

    /**
     * 设置高度
     */
    setHeight(height) {
        this.height = height;
        this.render();
        return this;
    }

    /**
     * 销毁图表
     */
    destroy() {
        if (this.chartInstance) {
            if (this.type === 'chartjs') {
                this.chartInstance.destroy();
            } else if (this.type === 'echarts') {
                this.chartInstance.dispose();
            }
            this.chartInstance = null;
        }
        super.destroy();
    }
}

// 导出组件
window.ChartContainer = ChartContainer;